# encoding: utf-8
# id                       | integer                     | not null default nextval('transacoes_id_seq'::regclass)
# data                     | date                        | 
# valor                    | numeric(10,2)               | 
# observacao               | character varying(255)      | 
# conta_id                 | integer                     | 
# tipo                     | integer                     | 
# created_at               | timestamp without time zone | not null
# updated_at               | timestamp without time zone | not null
# type                     | character varying(255)      | 
# quitada                  | boolean                     | default false
# usuario_id               | integer                     | 
# transacao_relacionada_id | integer                     | 
# parcelado_id             | integer                     | 
# ordem                    | integer                     | 
class Despesa < Debito
	attr_protected
	
	belongs_to :usuario
	
	validates :usuario_id, :data,
		:presence => true  

	#
	#
  def before_save
  	self.quitada = self.quitada || (self.data <= Date.today)
  end

	#
	#
	def self.listar(usuario, conta, periodo)
		return if usuario.nil? or !usuario.is_a? Usuario
		return if !periodo.nil? and !periodo.is_a? Date
		
		conditions = []
		values = []

		unless conta.nil?
			conditions << "conta_id = ?"
			values << conta
		end

		unless periodo.nil?
			conditions << "date_part('month', data) = ?"
			conditions << "date_part('year', data) = ?"
			values << periodo.month
			values << periodo.year
		end

		return usuario.despesas.where(values.prepend(conditions.join(" and ")))
	end
end
